# -*- coding: utf-8 -*-
# @Time    : 2020/3/15 下午5:15
# @Author  : lilong

from collections import Iterable, Iterator  # 引入Iterable和Iterator


def testLoop():
    arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    for e in arr:
        print(e, end="\t")


#  方法一：使用()定义生成器
gen = (x * x for x in range(10))


#  方法二：使用yield定义generator函数
def fibonacci(maxNum):
    """斐波那契数列的生成器"""
    a = b = 1
    for i in range(maxNum):
        yield a
        a, b = b, a + b


def testIterable():
    print("方法一，0-9的平方数：")
    for e in gen:
        print(e, end="\t")
    print()

    print("方法二，斐波那契数列：")
    fib = fibonacci(10)
    for n in fib:
        print(n, end="\t")
    print()

    print("内置容器的for循环：")
    arr = [x * x for x in range(10)]
    for e in arr:
        print(e, end="\t")
    print()

    print()
    print(type(gen))
    print(type(fib))
    print(type(arr))


def testIsIterator():
    print("是否为Iterable对象：")
    print(isinstance([], Iterable))
    print(isinstance({}, Iterable))
    print(isinstance((1, 2, 3), Iterable))
    print(isinstance(set([1, 2, 3]), Iterable))
    print(isinstance("string", Iterable))
    print(isinstance(gen, Iterable))
    print(isinstance(fibonacci(10), Iterable))
    print("是否为Iterator对象：")
    print(isinstance([], Iterator))
    print(isinstance({}, Iterator))
    print(isinstance((1, 2, 3), Iterator))
    print(isinstance(set([1, 2, 3]), Iterator))
    print(isinstance("string", Iterator))
    print(isinstance(gen, Iterator))
    print(isinstance(fibonacci(10), Iterator))


def testNextItem():
    print("将Iterable对象转成Iterator对象：")
    l = [1, 2, 3]
    itrL = iter(l)
    print(next(itrL))
    print(next(itrL))
    print(next(itrL))

    print("next()函数遍历迭代器元素：")
    fib = fibonacci(4)
    print(next(fib))
    print(next(fib))
    print(next(fib))
    print(next(fib))
    # print(next(fib))


class NumberSequence:
    """生成一个间隔为step的数字系列"""

    def __init__(self, init, step, max=100):
        self.__data = init
        self.__step = step
        self.__max = max

    def __iter__(self):
        print("__iter__")
        return self

    def __next__(self):
        if (self.__data < self.__max):
            tmp = self.__data
            self.__data += self.__step
            return tmp
        else:
            raise StopIteration


def testNumberSequence():
    numSeq = NumberSequence(0, 5, 20)
    print(isinstance(numSeq, Iterable))
    print(isinstance(numSeq, Iterator))
    for n in numSeq:
        print(n, end="\t")


# testLoop()
# testIterable()
# testIsIterator()
# testNextItem()
testNumberSequence()
